﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace StartSearchXP
{
    public partial class Form1 : Form
    {
        public string[] filesuser;
        public string[] filesallusers;
        public string startmenupath_curuser;
        public string startmenupath_allusers;
        string curuserpath = Environment.ExpandEnvironmentVariables(StartSearchXP.Properties.Settings.Default.custompath_currentuser);
        string alluserpath = Environment.ExpandEnvironmentVariables(StartSearchXP.Properties.Settings.Default.custompath_allusers);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            //these declarations do not work, need to parse the directory it outputs rather than doing .tostring, since it only outputs the name of the variable.
            if (StartSearchXP.Properties.Settings.Default.custompath_allusers == "")
            {
                showhelp();
                StartSearchXP.Properties.Settings.Default.custompath_allusers = Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu);
            }
            if (StartSearchXP.Properties.Settings.Default.custompath_currentuser == "")
            {
                StartSearchXP.Properties.Settings.Default.custompath_currentuser = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu);
            }
            //event handler declarations
            listBox1.DoubleClick += new EventHandler(listBox1_DoubleClick);
            listBox1.KeyUp += new KeyEventHandler(listBox1_KeyUp);
            textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);

            //indexing start menu for the current user
            rebuild_index();
            Properties.Settings.Default.Save();
        }

        #region eventhandlers

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            showhelp();
        }


        void listBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) { launchapp(listBox1.SelectedItem.ToString()); }
        }

        void listBox1_DoubleClick(object sender, EventArgs e)
        {
            launchapp(listBox1.SelectedItem.ToString());
            
        }


        void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode.Equals(Keys.Enter)) { search(textBox1.Text); }
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            options options = new options();
            options.ShowDialog();
        }

        private void rebuildSearchIndexToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rebuild_index();
            MessageBox.Show("Rebuilding done.");
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("StartSearchXP allows " + Environment.OSVersion.VersionString +  " users to quickly search through their start menu\nAnd execute any programs found.\nCreated by Ced.\n\nThere were no huskies, foxes, ferrets, dragons, wolves, meerkats,\nhyenas or any combination of the above been harmed in the making of this program.\n\n\nMay the yiff be with you.","Rawr.",MessageBoxButtons.AbortRetryIgnore,MessageBoxIcon.Asterisk,MessageBoxDefaultButton.Button1);
        }
        #endregion

        #region functions
        void search(string searchstring)
        {
            listBox1.Items.Clear();
            foreach (string result in filesuser)
            {
                if (result.ToUpper().Contains(searchstring.ToUpper())) 
                {
                    if (result.Remove(0, curuserpath.Length).Replace(".lnk", "") != "")
                    {
                         listBox1.Items.Add(result.Remove(0, curuserpath.Length).Replace(".lnk", "")); 
                    }
                   
                }
            }
            foreach (string result in filesallusers)
            {
                if (result.ToUpper().Contains(searchstring.ToUpper()))
                {
                    if (result.Remove(0, alluserpath.Length).Replace(".lnk", "") != "")
                    {
                         listBox1.Items.Add(result.Remove(0, alluserpath.Length).Replace(".lnk", ""));
                    }
                   
                }
            }
            



        }
        void launchapp(string appname)
        {

            //i know i know, this is a very hacky and sloppy way, but i'm too lazy and cba to fix it,
            //besides, it should work if everything else is fine :V
            try
            {
                Process p = new Process();
                p.StartInfo = new ProcessStartInfo(alluserpath + appname.Replace(".lnk", ""))
                {
                    RedirectStandardOutput = false,
                    UseShellExecute = true,
                    CreateNoWindow = false
                };
                p.Start();
            }
            catch (Exception)
            {
                Process p = new Process();
                p.StartInfo = new ProcessStartInfo(curuserpath + appname.Replace(".lnk", ""))
                {
                    RedirectStandardOutput = false,
                    UseShellExecute = true,
                    CreateNoWindow = false
                };
                p.Start();
            }

        }
        void rebuild_index()
        {
            //Indexing start menu with the freshest variables from the xml files~
            try
            {
                curuserpath = Environment.ExpandEnvironmentVariables(StartSearchXP.Properties.Settings.Default.custompath_currentuser);
                alluserpath = Environment.ExpandEnvironmentVariables(StartSearchXP.Properties.Settings.Default.custompath_allusers);
                filesuser = System.IO.Directory.GetFileSystemEntries(curuserpath, "*", System.IO.SearchOption.AllDirectories);
                filesallusers = System.IO.Directory.GetFileSystemEntries(alluserpath, "*", System.IO.SearchOption.AllDirectories);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured when updating search index: " + ex.Message.ToString() + "\n\nIf this is the first time you run this program, try editting the settings (right click anywhere and hit options).");

            }

        }
        void showhelp()
        {
            MessageBox.Show("Welcome!\nThis program is designed for use as a quick start menu browser,\n I found this handy feature lacking in windows xp, and decided to make it myself!\nAnywho, some basic tips: \n-first, if you right click anywhere (except the search bar) on this program, a small menu will pop up with options\nI'm sure you know what to do with it.\n- Second, to just state the obvious, type your search string into the textbox at the top of the program and hit enter,\nThen select an item from the list and either double click it or hit enter again to launch it.\n\nAnd if i forgot anything, just yell and bash keys, always works for me!\n\n\nCreated by Ced 2010", "Helpfulness!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        #endregion



    }
}
